package com.zhifou.handler;

import com.zhifou.annotation.Access;
import com.zhifou.constants.RedisPrefix;
import com.zhifou.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author
 * @description TODO
 * @date 2023-02-24 10:23
 */
@Component
@Slf4j
public class AccessInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("----->年龄限制拦截器");
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            // 获取方法上的权限
            Access annotation = method.getAnnotation(Access.class);
            if (null != annotation) {
                String token = request.getHeader("token");
                // 用户信息
                User user = (User) redisTemplate.opsForValue().get(RedisPrefix.TOKEN_USER_LOGIN + token);
                if (user.getAge() < annotation.age()) {
                    throw new Exception("年龄太小，禁止查看美女信息！");
                } else {
                    return true;
                }
            }
        }
        return true;
    }
}
